import os
import sys
import json
import platform


class ParseCatalog(object):

    def __init__(self, ApiCatalogue, ApidocJson, ResTemplate, ResStatus):
        self.api = ApiCatalogue
        self.apidoc_json = ApidocJson
        self.response_status = ResStatus
        self.doc_temp = ResTemplate
        self.define_catalogue = []
        self.apidoc_order = []

    def start(self):
        apis = self.api.split("\n")
        path_a, name_a = "", ""
        for api_txt in apis:
            if not api_txt:
                continue
            if api_txt.startswith("-"):
                path_a, name_a = api_txt[1:].split(" ")
                self.apidoc_order.append(path_a)
            elif api_txt.startswith("  -"):
                path_b, name_b = api_txt[3:].split(" ")
                tmp = '%s %s-%s' % (path_a + path_b, name_a, name_b)
                self.define_catalogue.append(tmp)
                self.apidoc_order.append(path_a + path_b)
            elif api_txt.startswith("    -"):
                path_c, name_c = api_txt[5:].split(" ")
                self.apidoc_order.append(path_c)
        self.makedirs("../../apidoc/conf")
        self.makedirs("../../apidoc/doc")
        self.write_define_catalogue()
        self.write_apidoc_json()
        self.write_appendix_status()
        self.run_shell()

    def makedirs(self, ref_path):
        path = os.path.normpath(os.path.join(__file__, ref_path))
        if not os.path.exists(path):
            os.makedirs(path)

    def write_define_catalogue(self):
        text_list = []
        path = os.path.normpath(os.path.join(__file__, "../../apidoc/conf/define_catalogue.py"))
        for define in self.define_catalogue:
            text_list.append('"""@%s%s %s"""\n' % ("api", "Define", define))
        with open(path, 'w', encoding='utf8') as f:
            f.writelines(text_list)
        print("[1] Write define_catalogue Done! [output -> apidoc/conf/define_catalogue.py]")

    def write_apidoc_json(self):
        self.apidoc_json["order"] = self.apidoc_order
        text = json.dumps(self.apidoc_json, indent=2)
        path = os.path.normpath(os.path.join(__file__, "../../apidoc/conf/apidoc.json"))
        with open(path, 'w', encoding='utf8') as f:
            f.writelines(text)
        print("[2] Write apidoc.json Done! [output -> apidoc/conf/apidoc.json]")

    def write_appendix_status(self):
        path = os.path.normpath(os.path.join(__file__, "../../apidoc/conf/appendix_status.py"))
        infos = ['"""']
        for x in self.doc_temp.split("\n"):
            if x.startswith("api"):
                x = "@" + x
            infos.append(x)
        text = '@apiSuccess (Response-status) %s %s'
        for status in sorted(list(self.response_status.keys())):
            infos.append(text % (status, self.response_status[status]))
        infos.append('"""')
        doc = [y + "\n" for y in infos]
        with open(path, 'w', encoding='utf8') as f:
            f.writelines(doc)
        print("[3] Write appendix_status Done! [output -> apidoc/conf/appendix_status.py]")

    def run_shell(self):
        system = platform.system()
        if system == "Windows":
            os.system(r".\apidoc_compile.bat")
        elif system == "Linux":
            os.system('bash ./apidoc_compile.sh')
        elif system == "Darwin":
            os.system('bash ./apidoc_compile.sh')
        else:
            return
        print("[4] ApiDoc Compile Done!")


if __name__ == "__main__":
    path = os.path.normpath(os.path.join(__file__, "../../"))
    sys.path.append(path)
    from libs.apidoc.apidoc_catalogue import ApiCatalogue
    from libs.apidoc.apidoc_json import ApidocJson
    from libs.apidoc.apidoc_res_status import ResTemplate
    from libs.enums.response_status import ResStatus
    handler = ParseCatalog(ApiCatalogue, ApidocJson, ResTemplate, ResStatus)
    handler.start()
